package Link;

public class LinkIterator {
	private doubleLink current;
	private doubleLink previous;
	private doublyLink list;
	
	public LinkIterator(doublyLink newlist) {
		this.list = newlist;
	}
	
	public void reset() {
		this.current = this.list.getFirst();
	}
	
	public boolean atEnd() {
		return (this.current.right == null);
	}
	
	public void nextLink() {
		this.previous = this.current;
		this.current = this.current.right;
	}
	
	public doubleLink getCurrent() {
		return this.current;
	}
	
	public void insertAfter(int dd) {
		if(this.list.isEmpty()) {
			this.list.insertFirst(dd);
			this.current = this.list.first;
		}else {
			doubleLink link = new doubleLink(dd);
			link.left = this.current;
			link.right = this.current.right;
			this.current.right.left = link;
			this.current.right = link;
			this.nextLink();
		}
	}
	
	public void insertBefore(int dd) {
		if(this.list.isEmpty()) {
			this.list.insertFirst(dd);
			this.current = this.list.first;
		}else {
			doubleLink link = new doubleLink(dd);
			link.left = this.current.left;
			link.right = this.current;
			this.current.left.right = link;
			this.current.left = link;
		}
	}
	
	public void deleteCurrent() {
		if(this.current.left == null) {
			this.list.first = this.current.right;
			this.reset();
		}else {
			this.previous.right = this.current.right;
			this.current.right.left = this.previous;
			if(this.atEnd()) {
				this.reset();
			}else {
				this.current = this.current.right;
			}
		}
	}
	
}
